package com.interview.javabase.tcpupd;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author: zsg
 * @description:
 * @date: 2019/6/8 21:25
 * @modified:
 */
public class UdpClient {
    public static void main(String[] args) {
        try {
            DatagramSocket datagramSocket = new DatagramSocket();

            byte[] bytes1 = "哈哈".getBytes();

            // 发送的时候要绑定ip + 端口
            DatagramPacket sendDatagramPacket = new DatagramPacket(bytes1,0,bytes1.length, InetAddress.getByName("127.0.0.1"),60001);
            sendDatagramPacket.setData(bytes1);
            datagramSocket.send(sendDatagramPacket);

            byte[] bytes = new byte[1024];
            DatagramPacket datagramPacket = new DatagramPacket(bytes,0,bytes.length);
            datagramSocket.receive(datagramPacket);
            byte[] data = datagramPacket.getData();

            // 此处注意在length 是包中的字节长度
            String s = new String(data, 0, datagramPacket.getLength());
            System.out.println(s);

            datagramSocket.close();
        }  catch (IOException e) {
            e.printStackTrace();
        }
    }
}
